package com.ruoyi.system.controller;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/toword")
public class MarkdownToWord {

    @GetMapping("/saveWord")
    public String saveWord(String name, String markdown) {
        // 获取当前日期和时间
        LocalDateTime currentDateTime = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
        // 将当前日期和时间格式化为字符串
        String formattedDateTime = currentDateTime.format(formatter);
        name = name + "-" + formattedDateTime+".docx";

        String filePath = "D:\\ruoyi\\uploadPath\\upload\\2025\\" + name;
        try {
            convertMarkdownToWord(markdown, filePath);
            System.out.println("文件已保存为: " + filePath);
            return "/profile/upload/2025/"+name;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



    public static void convertMarkdownToWord(String markdown, String filePath) throws IOException {
        // 将 Markdown 转换为 HTML
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markdown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        String html = renderer.render(document);

        // 创建一个新的 Word 文档
        XWPFDocument doc = new XWPFDocument();

        // 解析 HTML 并将内容添加到 Word 文档中
        Document jsoupDoc = Jsoup.parse(html);
//        Elements elements = jsoupDoc.body().children();
        // 替换原有for循环解析逻辑
        Elements elements = jsoupDoc.body().children(); // 只处理直接子元素
        for (Element element : elements) {
            XWPFParagraph paragraph = doc.createParagraph();

            // 处理段落内容
            for (org.jsoup.nodes.Node node : element.childNodes()) {
                if (node instanceof TextNode) {
                    String text = ((TextNode) node).text().trim();
                    if (!text.isEmpty()) {
                        paragraph.createRun().setText(text);
                    }
                } else if (node instanceof Element) {
                    Element childElem = (Element) node;
                    if ("img".equalsIgnoreCase(childElem.tagName() ) || "png".equalsIgnoreCase(childElem.tagName())) {
                        handleImage(doc, paragraph, childElem);
                    }
                    // 可扩展处理其他标签...
                }
            }
        }
        // 将 Word 文档保存到指定路径
        try (FileOutputStream out = new FileOutputStream(filePath)) {
            doc.write(out);
        }
    }

    // 在类中添加路径转换方法
    private static String convertImageUrlToLocalPath(String imgUrl) {
        // 将/dev-api/profile/images/ 转换为本地存储路径
        return imgUrl.replace("/dev-api/profile/images/", "D:\\ruoyi\\uploadPath\\images\\");
    }

    private static void addImageToDocument(XWPFDocument doc, String imgPath) throws Exception {
        XWPFParagraph paragraph = doc.createParagraph();
        XWPFRun run = paragraph.createRun();

        try (FileInputStream is = new FileInputStream(imgPath)) {
            String fileName = imgPath.substring(imgPath.lastIndexOf(".") + 1);
            int pictureType = getPictureType(fileName);

            run.addPicture(is,
                    pictureType,
                    imgPath,
                    Units.toEMU(400),  // 宽度
                    Units.toEMU(300)); // 高度
        }
    }
    // 单独处理图片的方法
    private static void handleImage(XWPFDocument doc, XWPFParagraph paragraph, Element imgElem) {
        try {
            String imgPath = convertImageUrlToLocalPath(imgElem.attr("src"));
            try (FileInputStream is = new FileInputStream(imgPath)) {
                paragraph.createRun().addPicture(
                        is,
                        getPictureType(FilenameUtils.getExtension(imgPath)),
                        imgPath,
                        Units.toEMU(400),
                        Units.toEMU(300)
                );
            }
        } catch (Exception e) {
            System.err.println("图片插入失败: " + imgElem.attr("src"));
        }
    }

    private static int getPictureType(String ext) {
        switch (ext.toLowerCase()) {
            case "png": return XWPFDocument.PICTURE_TYPE_PNG;
            case "jpg":
            case "jpeg": return XWPFDocument.PICTURE_TYPE_JPEG;
            default: return XWPFDocument.PICTURE_TYPE_PNG;
        }
    }

}
